package com.syz.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.syz.mall.constant.RedisConstant;
import com.syz.mall.mapper.ProductMapper;
import com.syz.mall.pojo.Product;
import com.syz.mall.pojo.query.ProductQuery;
import com.syz.mall.service.IProductService;
import com.syz.mall.util.LayUITableResult;
import com.syz.mall.util.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ProductServiceImpl implements IProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.SUPPORTS)
    @Override
    public LayUITableResult selectByPage(ProductQuery productQuery) {
        PageHelper.startPage(productQuery.getPage(), productQuery.getLimit());
        List<Product> list = productMapper.selectAll(productQuery);
        PageInfo pageInfo = new PageInfo(list);
        long totalCount = pageInfo.getTotal();
        return LayUITableResult.ok((int)totalCount, list);
    }
    @Override
    public boolean deleteAll(Integer[] ids) {
        int count = productMapper.deleteAll(ids);
        return count == ids.length;
    }

    @Override
    public boolean deleteById(Integer id) {
        int count = productMapper.deleteByPrimaryKey(id);
        return count == 1;
    }

    @Override
    public boolean add(Product product) {
        int count = productMapper.insertSelective(product);

        String mainImage = product.getMainImage();
        String imageName = mainImage.substring(QiniuUtils.URL.length());
        redisTemplate.opsForSet().add(RedisConstant.UPLOAD_IMAGE_TO_DB, imageName);

        return count == 1;
    }

    @Override
    public Product selectById(Integer id) {
        return productMapper.selectByPrimaryKey(id);
    }

    @Override
    public boolean update(Product product) {
        int count =productMapper.updateByPrimaryKeySelective(product);

        String mainImage = product.getMainImage();
        String imageName = mainImage.substring(QiniuUtils.URL.length());
        redisTemplate.opsForSet().add(RedisConstant.UPLOAD_IMAGE_TO_DB, imageName);

        return count==1;
    }

    @Override
    public boolean changeStatus(Integer id, Integer status) {
        int count =productMapper.changeStatus(id,status);
        return count==1;
    }
}
